<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/1/2/002
 * Time: 10:15
 */

namespace Home\Controller;

use Think\Controller;
class SortController extends Controller
{
    //初始化方法
    protected function _initialize()
    {
        //检测用户是否登陆 并定义全局变量
        if(isset($_SESSION['msg']['id'])){
            define('UID', $_SESSION['msg']['id']);
        } else {
            $this->redirect('/index.php/Home/Login/login');
        }
    }

    //获取展示界面
    public function show() {
        $this->display('Sort/index');
    }
    //榜单 设员工荣誉排行榜，日榜单、周榜单、月榜单，针对榜单进行线下激励；
    public function getSort() {
        $register = M('Register');
        $type = I('type', 0, 'intval');  //1代表日 2代表周 3代表月
        $p = I('p', 0, 'intval');
        if (!$type) {
            $this->ajaxReturn(V(0, '参数错误'));
        }
        $defaultDate = date("Y-m-d");

        if ($type == 1) {
            $where['time'] = ['eq', $defaultDate];
        } else if($type == 2) {
            //$first =1 表示每周星期一为开始日期 0表示每周日为开始日期
            $first = 1;
            $w =date('w');  //本周第几天
            //获取本周开始日期，如果$w是0，则表示周日，减去 6 天
            $week_start=date('Y-m-d',strtotime("$defaultDate -".($w ? $w - $first : 6).' days'));
            //本周结束日期
            $week_end=date('Y-m-d',strtotime("$week_start +6 days"));
            $where['time'] = [['egt', $week_start], ['elt', $week_end]];
        } else if($type == 3) {
            $firstday = date('Y-m-01', strtotime($defaultDate));
            $lastday = date('Y-m-d', strtotime("$firstday +1 month -1 day"));
            $where['time'] = [['egt', $firstday], ['elt', $lastday]];
        }

        $list = $register->alias('u')->join('__REWARD__ r on u.id = r.uid')
            ->field('u.tel, u.commissions, sum(r.money) as sum,IF(u.headimg<>"0", u.headimg, "/Public/images/head.png") as headimg,IF(u.register_name<>"0", u.register_name, CONCAT("员工-",u.id)) as register_name')
            ->group('u.id')
            ->page($p)
            ->limit(20)
            ->order('sum desc')
            ->where($where)->select();

        $this->ajaxReturn(V(1, '统计列表', $list ? $list : []));
    }


}